package com.jh.paymentchannel.helipay.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.helipay.util.HeliPayBase;
import com.jh.paymentchannel.util.Util;

import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;

@EnableScheduling
@Configuration
public class HK_HistoryService {
	@Autowired
	Util util;

	@Value("${schedule-task.on-off}")
	private String scheduleTaskOnOff;

	private static final Logger log = LoggerFactory.getLogger(HK_HistoryService.class);

	/* 六点执行一次 */
	@Scheduled(cron = "0 0 6 * * ?")
	public void theWayOnHK() {
		/* 获取开始到结束的五分钟时间段[00:00:00~00:04:00] */
		if ("true".equals(scheduleTaskOnOff)) {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String end = sdf.format(date) + " 00:00";
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(date.getTime() - 86400000);
			String start = sdf.format(calendar.getTime()) + " 00:00";
			/* 根据执行时间查询任务 */
			RestTemplate restTemplate = new RestTemplate();
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/find";
			log.info("==============" + url + "===============");
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("start", start);
			requestEntity.add("end", end);
			requestEntity.add("type", "1");
			log.info("接口/v1.0/paymentchannel/automaticrepaymenttask/find--参数================" + start + "," + end);
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/paymentchannel/automaticrepaymenttask/find--RESULT================" + result);
			JSONObject jsonObject = JSONObject.fromObject(result);
			List<JSONObject> list = null;
			if (jsonObject.containsKey("result")) {
				list = (List) jsonObject.get("result");
			} else {
				return;
			}

			for (int i = 0; i < list.size(); i++) {
				JSONObject art = list.get(i);
				log.info("==============" + art.toString() + "=============");
				String P5_orderId = art.getString("orderCode");
				String P3_userId = art.getString("userId");
				String P4_bindId = art.getString("bindId");
				String P8_orderAmount = art.getString("realAmount");
				// P8_orderAmount =
				// String.valueOf((Float.valueOf(P8_orderAmount) + 0.5));
				// P8_orderAmount = String.valueOf(new
				// BigDecimal(P8_orderAmount).divide(new
				// BigDecimal("0.9998"),2,RoundingMode.DOWN));
				String amount = art.getString("amount");
				String status = art.getString("status");
				String payCard = art.getString("payCard");
				if ("1".equals(status))
					continue;
				/* 根据bindid查询用户到账卡号、手机号 */
				uri = util.getServiceUrl("paymentchannel", "error url request!");
				url = uri.toString() + "/v1.0/paymentchannel/hlregister/findbycard";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("bindId", P4_bindId);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/paymentchannel/hlregister/findbycard--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				String bankCard = null;
				String phone = null;
				String loginPhone = null;
				if (jsonObject.containsKey("result")) {
					JSONObject jobj = jsonObject.getJSONObject("result");
					bankCard = jobj.getString("bankCard");
					phone = jobj.getString("phone");
					loginPhone = jobj.getString("loginPhone");
				} else {
				}
				/* 根据userid查询用户贴牌 */
				uri = util.getServiceUrl("user", "error url request!");
				url = uri.toString() + "/v1.0/user/find/by/userid";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("userId", P3_userId);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/user/find/by/userid--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				String brandId = null;
				if (jsonObject.containsKey("result")) {
					JSONObject jobj = jsonObject.getJSONObject("result");
					brandId = jobj.getString("brandId");
				} else {
				}
				// int sjs = (int)(2+Math.random()*2);
				/*
				 * int num = amount.indexOf("."); Double littlebalance =
				 * Double.parseDouble("0."+amount.substring(num+1,
				 * amount.length()));//小数金额 String amountZ = amount.substring(0,
				 * num);//去掉小数金额 int surplus = Integer.valueOf(amountZ)%2;//整除余数
				 * int amountEll = Integer.valueOf(amountZ)-surplus; int amountE
				 * = (int)(Double.valueOf(amountEll)/2); amountE =
				 * amountE+(int)(Math.random()*(amountE-5)); int amountEEE =
				 * amountEll - amountE;
				 */

				uri = util.getServiceUrl("paymentchannel", "error url request!");
				url = uri.toString() + "/v1.0/paymentchannel/spend/find/byordercode";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("orderCode", P5_orderId);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/paymentchannel/spend/find/byordercode--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				List<JSONObject> listspend = null;
				if (jsonObject.containsKey("result")) {
					listspend = (List) jsonObject.get("result");
					log.info("list================" + listspend.toString());
					int statall = 0;
					for (int ii = 0; ii < 2; ii++) {
						statall += listspend.get(ii).getInt("status");
					}
					log.info("statall================" + statall);
					if (statall != 6) {
						uri = util.getServiceUrl("paymentchannel", "error url request!");
						url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("orderCode", P5_orderId);
						requestEntity.add("status", "2");// 失败
						result = restTemplate.postForObject(url, requestEntity, String.class);
						log.info("接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
								+ result);
						continue;
					}
				} else {
					continue;
				}
				/*
				 * String amountEE = listspend.get(0).getString("amount");
				 * String amountE = listspend.get(1).getString("amount"); int
				 * checknum = 0; DecimalFormat decimalFormat = new
				 * DecimalFormat("0.00");
				 * decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
				 */
				/*
				 * for(int ii=0;ii<2;ii++) { uri = util.getServiceUrl("facade",
				 * "error url requ	est!"); url = uri.toString() +
				 * "/v1.0/facade/topup"; requestEntity = new
				 * LinkedMultiValueMap<String, String>();
				 * requestEntity.add("phone", loginPhone);
				 * requestEntity.add("channe_tag", "HL_PAY");
				 * requestEntity.add("order_desc", "信用卡还款任务");
				 * requestEntity.add("brand_id", brandId);
				 * requestEntity.add("bank_card", payCard); if(ii==1) { //String
				 * amountEE = decimalFormat.format(new
				 * BigDecimal(String.valueOf(amountEEE)).add(new
				 * BigDecimal(littlebalance+surplus)));
				 * requestEntity.add("amount", amountEE); }else {
				 * requestEntity.add("amount", String.valueOf(amountE)); }
				 * log.info("接口/v1.0/facade/topup--参数================"+
				 * requestEntity); result = restTemplate.postForObject(url,
				 * requestEntity, String.class);
				 * log.info("接口/v1.0/facade/topup--RESULT================"+
				 * result); jsonObject = JSONObject.fromObject(result);
				 * if(CommonConstants.SUCCESS.equals(jsonObject.get("resp_code")
				 * )) { checknum++; uri = util.getServiceUrl("paymentchannel",
				 * "error url request!"); url = uri.toString() +
				 * "/v1.0/paymentchannel/spend/update/byordercode";
				 * requestEntity = new LinkedMultiValueMap<String, String>();
				 * requestEntity.add("orderCode", P5_orderId); if(ii==1) {
				 * requestEntity.add("amount", amountEE); }else {
				 * requestEntity.add("amount", String.valueOf(amountE)); }
				 * requestEntity.add("status", "3");//充值成功 result =
				 * restTemplate.postForObject(url, requestEntity, String.class);
				 * log.info(
				 * "接口/v1.0/paymentchannel/spend/update/byordercode--RESULT================"
				 * +result); }else { uri = util.getServiceUrl("paymentchannel",
				 * "error url request!"); url = uri.toString() +
				 * "/v1.0/paymentchannel/spend/update/byordercode";
				 * requestEntity = new LinkedMultiValueMap<String, String>();
				 * requestEntity.add("orderCode", P5_orderId); if(ii==1) {
				 * requestEntity.add("amount", amountEE); }else {
				 * requestEntity.add("amount", String.valueOf(amountE)); }
				 * requestEntity.add("status", "5");//充值失败 result =
				 * restTemplate.postForObject(url, requestEntity, String.class);
				 * log.info(
				 * "接口/v1.0/paymentchannel/spend/update/byordercode--RESULT================"
				 * +result); } }
				 */
				/*
				 * log.info("============================"+checknum+
				 * "============================"); if(checknum==2) { uri =
				 * util.getServiceUrl("paymentchannel", "error url request!");
				 * url = uri.toString() +
				 * "/v1.0/paymentchannel/automaticrepaymenttask/update";
				 * requestEntity = new LinkedMultiValueMap<String, String>();
				 * requestEntity.add("orderCode", P5_orderId);
				 * requestEntity.add("status", "3");//充值成功 result =
				 * restTemplate.postForObject(url, requestEntity, String.class);
				 * log.info(
				 * "接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
				 * +result); }else { uri = util.getServiceUrl("paymentchannel",
				 * "error url request!"); url = uri.toString() +
				 * "/v1.0/paymentchannel/automaticrepaymenttask/update";
				 * requestEntity = new LinkedMultiValueMap<String, String>();
				 * requestEntity.add("orderCode", P5_orderId);
				 * requestEntity.add("status", "5");//充值失败 result =
				 * restTemplate.postForObject(url, requestEntity, String.class);
				 * log.info(
				 * "接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
				 * +result); }
				 */
				uri = util.getServiceUrl("paymentchannel", "error url request!");
				url = uri.toString() + "/v1.0/paymentchannel/pay/creditcardpayment";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("channe_tag", "CREDICTPAY");
				requestEntity.add("order_desc", "还款任务");
				requestEntity.add("brand_id", brandId);
				requestEntity.add("cardNo", bankCard);
				requestEntity.add("phone", loginPhone);
				requestEntity.add("orderCode", P5_orderId);
				requestEntity.add("userid", P3_userId);
				requestEntity.add("amount", P8_orderAmount);
				log.info("接口/v1.0/paymentchannel/pay/creditcardpayment--参数================" + requestEntity);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/paymentchannel/pay/creditcardpayment--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				if ("000000".equals(jsonObject.getString("resp_code"))) {
					uri = util.getServiceUrl("paymentchannel", "error url request!");
					url = uri.toString() + "/v1.0/paymentchannel/topup/queryOrder";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("P1_bizType", "TransferQuery");
					requestEntity.add("P2_orderId", P5_orderId);
					requestEntity.add("P3_customerNumber", HeliPayBase.MERCHANT_NO);
					result = restTemplate.postForObject(url, requestEntity, String.class);
					log.info("接口/v1.0/paymentchannel/topup/queryOrder--RESULT================" + result);
					jsonObject = JSONObject.fromObject(result);
					if ("订单查询成功".equals(jsonObject.getString("message"))) {
						JSONObject jsonObj = jsonObject.getJSONObject("json");
						if ("0000".equals(jsonObj.getString("rt2_retCode"))) {
							if (jsonObj.containsKey("rt7_orderStatus")) {
								/*
								 * INIT已接收 DOING处理中 SUCCESS成功 FAIL失败 REFUND退款
								 */
								if ("INIT".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
										|| "DOING".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
										|| "SUCCESS".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									uri = util.getServiceUrl("paymentchannel", "error url request!");
									url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("orderCode", P5_orderId);
									requestEntity.add("status", "1");
									result = restTemplate.postForObject(url, requestEntity, String.class);
									log.info(
											"接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
													+ result);
								}
							}
						} else {
							if (jsonObj.containsKey("rt7_orderStatus")) {
								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									uri = util.getServiceUrl("paymentchannel", "error url request!");
									url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("orderCode", P5_orderId);
									requestEntity.add("status", "4");// 退款
									result = restTemplate.postForObject(url, requestEntity, String.class);
									log.info(
											"接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
													+ result);
								}
								if ("FAIL".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
									uri = util.getServiceUrl("paymentchannel", "error url request!");
									url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("orderCode", P5_orderId);
									requestEntity.add("status", "2");// 失败
									result = restTemplate.postForObject(url, requestEntity, String.class);
									log.info(
											"接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"
													+ result);
								}
							}
						}
					}
				}
			}
		}
	}
}
